package com.demo.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
//美团
public class RedisUtil {
    private static JedisPool jedisPool;

    static {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(50);
        poolConfig.setMaxIdle(10);
        poolConfig.setMinIdle(5);
        poolConfig.setTestOnBorrow(true);
        jedisPool = new JedisPool(poolConfig, "localhost", 6379);
    }

    public static void main(String[] args) {
        final String key = "unique_id_key";

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                //11116 是开始的
                try (Jedis jedis = jedisPool.getResource()) { // 获取连接
                    for (int j = 0; j < 1000; j++) {
                        long id = jedis.incr(key);
                        System.out.println(Thread.currentThread().getName() + " 生成的唯一 ID: " + id);
                    }
                } // 自动释放连接
            }, "Thread-" + i).start();
        }

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (jedisPool != null) {
                jedisPool.close();
                System.out.println("JedisPool 已关闭");
            }
        }));
    }
}
